import { getUnreadMessageCount } from '@/components/im/api/message'
import { patch } from '@/store/module'
import { isDef } from '@web-utils/core'

export default {
  namespaced: true,
  state: {
    unreadCount: 0,
    chatWindowVisible: false,
    activeThreadId: null
  },
  mutations: {
    patch,
    hideChatWindow(state) {
      state.chatWindowVisible = false
    },
    toggleChatWindow(state, visible) {
      state.chatWindowVisible = isDef(visible) ? (state.chatWindowVisible = visible) : !state.chatWindowVisible
    },
    adjustUnreadCount(state, count) {
      let unreadCount = state.unreadCount
      unreadCount += count
      state.unreadCount = unreadCount < 0 ? 0 : unreadCount
    },
    setUnreadCount(state, count) {
      state.unreadCount = count
    },
    setActiveThreadId(state, activeThreadId) {
      state.activeThreadId = activeThreadId
    }
  },
  actions: {
    async getUnreadMessageCount({ commit }) {
      const res = await getUnreadMessageCount()
      commit('patch', { unreadCount: res.data.data })
    }
  }
}
